package com.qf.admin.controller;

import com.qf.common.http.Result;
import com.qf.common.http.ResultCode;
import com.qf.service.impl.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {
    @Autowired
    private AdminService adminService;
    //跳转到登录页面
    @RequestMapping({"/", "login"})
    public String toLogin() {
        return "login";
    }
    //执行登录的方法
    @RequestMapping("login.do")
    public String doLogin(Model model,
                          @RequestParam(value = "username", required = true) String username,
                          @RequestParam(value = "password", required = true) String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            if (subject.isAuthenticated()) {
                return "forward:/index";
            }
        } catch (AuthenticationException e) {
        }
        model.addAttribute("username", username);
        model.addAttribute("error", ResultCode.LOGIN_ERROR.getDescription());
        return "forward:/";
    }


}
